﻿/*
 * 登录解析
 * 处理登录逻辑，验证客户段提交的账号密码，保存登录信息
 */
using System;
using Infrastructure;
using Infrastructure.Cache;
using Infrastructure.Helpers;
using Infrastructure.Helpers.PwdHelper;
using Infrastructure.Helpers.RSAHelper;
using NetTaste;
using Newtonsoft.Json;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;


namespace OpenAuth.App.SSO
{
    public class LoginParse
    {

        //这个地方使用IRepository<User> 而不使用UserManagerApp是防止循环依赖
        public IRepository<User,OpenAuthDBContext> _app;
        private ICacheContext _cacheContext;
        private AppManager _appInfoService;

        public LoginParse( AppManager infoService, ICacheContext cacheContext, IRepository<User,OpenAuthDBContext> userApp)
        {
            _appInfoService = infoService;
            _cacheContext = cacheContext;
            _app = userApp;
        }

        public  LoginResult Do(PassportLoginRequest model)
        {
            var result = new LoginResult();
            try
            {
                model.Trim();
   
                //检查登录名是否填写
                if (string.IsNullOrEmpty(model.Account))
                {
                    result.Code = 500;
                    result.Message = "登录名不可为空";
                    return result;
                }

                //检查密码是否填写
                if (string.IsNullOrEmpty(model.Password))
                {
                    result.Code = 500;
                    result.Message = "密码不可为空";
                    return result;
                }

                //RSA解密得到原始值
                model.Password = RSAEncryptUtil.Decrypt(model.Password);

                //获取用户信息
                User userInfo = null;

                userInfo = _app.FirstOrDefault(u => u.Account == model.Account);

                if (userInfo == null)
                {
                    result.Code = 500;
                    result.Message = "用户不存在或密码错误";
                    return result; 
                }

         

                //检查与数据库中的密文是否一致
                if (PwdHelper.Encrypt(model.Password) != userInfo.Password)
                {
                    result.Code = 500;
                    result.Message = "用户不存在或密码错误";
                    return result; 
                }

                if (userInfo.Status != 0)
                {
                    result.Code = 500;
                    result.Message = "账号状态异常，可能已停用";
                    return result;
                }

                var currentSession = new UserAuthSession
                {
                    Account = model.Account,
                    Name = userInfo.Name,
                    AppKey = model.AppKey,
                    Token = Guid.NewGuid().ToString("N"),
                    CreateTime = DateTime.Now  
                };

                //加密登录信息
                string Token = AESHelpers.Encrypt(JsonConvert.SerializeObject(currentSession));

                //Token过期时间
                int TokenExpire = string.IsNullOrEmpty(ConfigHelper.GetConfig("TokenExpire")) ? 240 : Convert.ToInt32(ConfigHelper.GetConfig("TokenExpire"));
               
                //创建Session
                _cacheContext.Set(Token, currentSession, DateTime.Now.AddHours(TokenExpire));

                result.Code = 200;
                result.Token = Token;
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }
    }
}